package phone.qyg.com.qyg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.baidu.PeripheryActivity;
import phone.qyg.com.qyg.adapter.FitnessMapAdapter;
import phone.qyg.com.qyg.model.MapItem;
import phone.qyg.com.qyg.model.MapTheme;
import phone.qyg.com.qyg.utils.AppHttpRequest;


/**
 * 作者：lblbh on 2017/6/1 09:51
 * 邮箱：lanbuhan@163.com
 * 功能：搜索地址
 */
@ContentView(R.layout.find_address)
public class FindAddressActivity extends BaseActivity implements OnGetSuggestionResultListener {

    public static final int ONE = 1;
    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.find_edit)
    AutoCompleteTextView find_edit;

    @ViewInject(R.id.hot_find_recycler)
    RecyclerView hot_find_recycler;

    @ViewInject(R.id.recycler)
    RecyclerView recycler;

    PoiSearch mPoiSearch = null;

    SuggestionSearch mSuggestionSearch = null;

    MapItem mapItem;

    int fitMapRequest;

    int type;

    @Override
    public void initData(Bundle savedInstanceState) {
// 初始化搜索模块，注册搜索事件监听
//        mPoiSearch = PoiSearch.newInstance();
//        mPoiSearch.setOnGetPoiSearchResultListener(this);

        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);

        ArrayAdapter sugAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line);
        find_edit.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }
                recycler.setVisibility(View.VISIBLE);
                hot_find_recycler.setVisibility(View.GONE);


                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                /*
                City city = JSONTool.requestJSONClazz(SharePrefUtil.getString(SharePrefUtil.KEY.CITY_CODE,null),City.class);
                String title = city.title;
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(title));

                */
                //必须添加城市名称
                String city = ApplicationConfig.CITY;
                if(null == mapItem){
                    city = SharePrefUtil.getString(SharePrefUtil.KEY.CITY,"");
                }else{
                    city = mapItem.city;
                }
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city((isRequestStr(city)?city:ApplicationConfig.CITY)));
            }
        });

        find_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    String key = getEditToString(find_edit);
                    if(type == 1){
                        SystemPrintl.systemPrintl("我在点击完成-------->>>>>>");

                        if(isRequestStr(key)){
                            Intent intent = new Intent();
                            intent.putExtra(ApplicationConfig.APP_KEY_TRANS,key);
                            setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
                            closeKeyboard();
                            FindAddressActivity.this.finish();//此处一定要调用finish()方法
                        }
                    }else if(type == ApplicationConfig.PERIPHERY_TYPE){
                        Bundle bundle = new Bundle();
                        bundle.putString(ApplicationConfig.APP_KEY_TRANS,key);
                        bundle.putParcelable(ApplicationConfig.APP_INFO_TWO_TRANS,mapItem);
                        closeKeyboard();
                        FindAddressActivity.this.finish();
                        TransformController.transformControllerIntPut(QXApplication.getContext(), PeripheryActivity.class,bundle);
                    }
                    return true;
                }
                return false;
            }
        });


        if(fitMapRequest == ApplicationConfig.FIT_MAP_TYPE){
            AppHttpRequest.fitMapRequest(new AppHttpRequest.OnFitmapRequestResult() {
                @Override
                public void onFitmapResult(List<MapTheme> themes) {
                    if(isRequestList(themes)){
                        GridLayoutManager girdLayoutManager = new GridLayoutManager(QXApplication.getContext(),4, GridLayoutManager.VERTICAL,false);
                        hot_find_recycler.setLayoutManager(girdLayoutManager);
                        recycler.setVisibility((fitMapRequest == ApplicationConfig.FIT_MAP_TYPE)?View.GONE:View.VISIBLE);
                        hot_find_recycler.setVisibility((fitMapRequest == ApplicationConfig.FIT_MAP_TYPE)?View.VISIBLE:View.GONE);
                        FitnessMapAdapter adapter = new FitnessMapAdapter(QXApplication.getContext(), themes, new FitnessMapAdapter.OnFitnessMapTitle() {
                            @Override
                            public void onClick(String title) {
                                Bundle bundle = new Bundle();
                                bundle.putString(ApplicationConfig.APP_KEY_TRANS,title);
                                bundle.putParcelable(ApplicationConfig.APP_INFO_TWO_TRANS,mapItem);
                                closeKeyboard();
                                FindAddressActivity.this.finish();
                                TransformController.transformControllerIntPut(QXApplication.getContext(), PeripheryActivity.class,bundle);
                            }
                        });
                        hot_find_recycler.setAdapter(adapter);
                    }
                }
            });
        }
    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
//        mPoiSearch.destroy();
        mSuggestionSearch.destroy();
        super.onDestroy();
    }

    @Override
    public void initViewHandler() {
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(layoutVerManager);
    }


    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        if (res == null || res.getAllSuggestions() == null) {
            return;
        }

        List<SuggestionResult.SuggestionInfo> infos =  res.getAllSuggestions();

        if(!isRequestList(infos))
            return;

        List<SuggestionResult.SuggestionInfo> delete = new ArrayList<SuggestionResult.SuggestionInfo>();
        for (int i=0,j=infos.size();i<j;i++){
            SuggestionResult.SuggestionInfo info =  infos.get(i);
            if(info.pt == null){
                delete.add(info);
            }
        }
        //删除没有用数据
        infos.removeAll(delete);
        final CommonAdapter adapter = new CommonAdapter<SuggestionResult.SuggestionInfo>(QXApplication.getContext(),R.layout.item_find_address,infos) {
            @Override
            protected void convert(ViewHolder holder, final SuggestionResult.SuggestionInfo info, final int position) {
                holder.setText(R.id.item_title,info.key);
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    SuggestionResult.SuggestionInfo obj = (SuggestionResult.SuggestionInfo) adapter.getData().get(position);

                    if(type == ApplicationConfig.PERIPHERY_TYPE){
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(ApplicationConfig.APP_INFO_TRANS,obj);
                        bundle.putParcelable(ApplicationConfig.APP_INFO_TWO_TRANS,mapItem);
                        closeKeyboard();
                        FindAddressActivity.this.finish();
                        TransformController.transformControllerIntPut(QXApplication.getContext(), PeripheryActivity.class,bundle);
                        return;
                    }

                    Intent intent = new Intent();
                    intent.putExtra(ApplicationConfig.APP_INFO_TRANS,obj);
                    setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
                    closeKeyboard();
                    FindAddressActivity.this.finish();//此处一定要调用finish()方法
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        recycler.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    @Override
    public void initSucessView() {
        Intent intent = getIntent();

        if(intent != null){
            Bundle bundle = intent.getBundleExtra(TransformController.ChangeKEY.INTENT_KEY);
            if(bundle != null){
                type = bundle.getInt(TransformController.ChangeKEY.BUNDLE_KEY,0);

                if(type == ApplicationConfig.PERIPHERY_TYPE){
                    mapItem =  bundle.getParcelable(TransformController.ChangeKEY.FITNESSMAP);
                    fitMapRequest =  bundle.getInt(TransformController.ChangeKEY.FIT_MAP_REQUEST);
                }
            }
        }

        closeKeyboard();
    }
}
